<template>
  <div class="repair-progress">
    <h1>维修进度更新</h1>
    
    <!-- 维修工单列表 -->
    <el-card class="repair-list">
      <el-table :data="repairOrders" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="工单ID" width="100" />
    <el-table-column prop="userId" label="用户" width="100">
      <template #default="scope">
        {{ formatUserId(scope.row.id) }}
      </template>
    </el-table-column>
    <el-table-column prop="deviceId" label="设备" width="100">
      <template #default="scope">
        {{ formatDeviceId(scope.row.id) }}
      </template>
    </el-table-column>
        <el-table-column prop="description" label="故障描述" />
        <el-table-column prop="reportTime" label="报修时间" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleUpdate(row)"
              :disabled="row.status === 2 || row.status === 3"
            >
              更新进度
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        @current-change="fetchData"
        layout="total, prev, pager, next, jumper"
      />
    </el-card>
    
    <!-- 更新进度对话框 -->
    <el-dialog v-model="dialogVisible" title="更新维修进度">
      <el-form :model="form" label-width="100px">
        <el-form-item label="当前状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="维修中" :value="1" />
            <el-option label="维修完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="维修备注">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            rows="4" 
            placeholder="请输入维修备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { listRepairorder, updateRepairorder } from '@/api/repairorder'
import RepairLayout from './RepairLayout.vue'
import {   listUser } from '@/api/user'
import { list as listDevice } from '@/api/device'
const users = ref([])
const devices = ref([])
import { useUserStore } from '@/store/user'

const userStore = useUserStore()


const loading = ref(false)
const dialogVisible = ref(false)
const repairOrders = ref([])
const total = ref(0)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: 1 // 默认查询维修中的工单
})

const form = reactive({
  id: null,
  status: 1,
  remark: ''
})

const statusMap = {
  0: { text: '待处理', type: 'warning' },
  1: { text: '维修中', type: 'primary' },
  2: { text: '维修完成', type: 'success' },
  3: { text: '已归档', type: 'info' }
}
onMounted(async () => {
  const [userRes, deviceRes] = await Promise.all([
    listUser(),
    listDevice()
  ])
  users.value = userRes 
  devices.value =  deviceRes
})

// 格式化用户ID显示
const formatUserId = (userId) => {
  const user = users.value.find(u => u.id === userId)
  return user ? user.userName : userId
}

// 格式化设备ID显示
const formatDeviceId = (deviceId) => {
  const device = devices.value.find(d => d.id === deviceId)
  return device ? device.deviceName : deviceId
}
const getStatusText = (status) => {
  return statusMap[status]?.text || '未知状态'
}

const getStatusType = (status) => {
  return statusMap[status]?.type || ''
}

const fetchData = async () => {
  loading.value = true
  try {
    const res = await listRepairorder(queryParams)
    repairOrders.value = res
    total.value = res.total
  } catch (error) {
    console.error('获取维修工单失败:', error)
    ElMessage.error('获取维修工单失败')
  } finally {
    loading.value = false
  }
}

const handleUpdate = (row) => {
  form.id = row.id
  form.status = row.status
  form.remark = ''
  dialogVisible.value = true
}

const submitUpdate = async () => {
  try {
    await updateRepairorder({
      ...form,
      userId: userStore.userId
    })
    ElMessage.success('更新成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('更新维修进度失败:', error)
    ElMessage.error('更新维修进度失败')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.repair-progress {
  padding: 20px;
}

.repair-list {
  margin-top: 20px;
}
</style>